﻿<%@ WebHandler Language="C#" Class="StepCheckPointResultSPCHandler" %>
/*Description: SPC处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20230216
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Configuration;
using System.Text;

public class StepCheckPointResultSPCHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness m_CommonObj = new uLMSCommonBusiness();
    uLMSStepCheckPointIBusiness m_CheckPointObj = uMESBusinessFactory.instance.GetuLMSStepCheckPointObject();

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetStepCheckInfoData"://获取检测项SPC基础数据 add by longb 2023-02-22
                    GetStepCheckInfoData(context);
                    break;
                case "SaveStepCheckPointSpcData"://检测项SPC基础数据保存 add by longb 2023-02-22
                    SaveStepCheckPointSpcData(context);
                    break;
                case "InitSpcWarningData"://初始化SPC异常预警页面数据 
                    InitSpcWarningData(context);
                    break;
                case "GetSpcWarningData"://获取检测项SPC异常预警数据 
                    GetSpcWarningData(context);
                    break;
                case "InitSpcWarningDialogData"://初始化SPC异常数据填写页面（弹窗） 
                    InitSpcWarningDialogData(context);
                    break;
                case "SaveSpcHistoryExperienceData"://保存失控处理历史经验 
                    SaveSpcHistoryExperienceData(context);
                    break;
                case "SaveSpcStepCheckItemDeal"://保存SPC失控处理记录 
                    SaveSpcStepCheckItemDeal(context);
                    break;
                case "ViewSpcStepCheckItemDeal"://查看失控处理记录
                    ViewSpcStepCheckItemDeal(context);
                    break;
                case "SaveSpcStepCheckDealResult"://保存失控处理记录审批结果
                    SaveSpcStepCheckDealResult(context);
                    break;
                case "GetSpcDealExperiencePool"://获取历史经验数据
                    GetSpcDealExperiencePool(context);
                    break;
                case "DeleSpcHistoryExperienceData"://删除历史经验数据
                    DeleSpcHistoryExperienceData(context);
                    break;
                case "GetWorflowStepListData"://获取工序数据
                    GetWorflowStepListData(context);
                    break;
                case "GetStepCheckPointDataByStepId"://获取检测项下拉数据（通过工序）
                    GetStepCheckPointDataByStepId(context);
                    break;
                case "GetSpcByCpkData"://获取CPK分析图
                    GetSpcByCpkData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    /// <summary>
    /// 获取cpk分析数据（绘制为图形统计）
    /// </summary>
    /// <param name="context"></param>
    public void GetSpcByCpkData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string ProductID = context.Request["productID"].ToString();
        string workflowID = context.Request["workflowID"].ToString();
        string workflowStepID = context.Request["workflowStepID"].ToString();
        string stepCheckPointID = context.Request["stepCheckPointID"].ToString();
        string startTime = context.Request["startTime"].ToString();
        string endTime = context.Request["endTime"].ToString();
        //string sPCRule = context.Request["sPCRule"].ToString();
        if (string.IsNullOrWhiteSpace(stepCheckPointID))
        {
            result.Result = false; result.Message = "未选择检测项";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //获取检测项下的所有的结果值（排除无效、批量加工的批次结果信息）
        DataTable dtCheckPointResult = new DataTable();
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT sp.spcrule,sp.spctype,sp.basevalue,sp.ceilfloat,sp.floorfloat,'' minYdata,'' maxYdata,'' currData,'' cpk,
                     spr.workcheckpointresultnote,spr.workcheckpointresultnotedis,sp.basevalue+(sp.floorfloat) updata,
                     sp.basevalue+(sp.ceilfloat) dwdata,spr.createdate,c.containername,e.fullname workname,
                     spr.spcstatus,r.description resourcedesc
                     FROM stepcheckpointresult spr 
                     LEFT JOIN employee e ON e.employeeid = spr.workerid
                     LEFT JOIN containerstepworkreport csw ON csw.containerstepworkreportid = spr.containerstepworkreportid AND csw.isuse = 0
                     LEFT JOIN resourcedef r ON r.resourceid = csw.resourceid
                     LEFT JOIN containercurrentinfo c ON c.containerid = spr.containerid
                     LEFT JOIN stepcheckpoint sp ON sp.stepcheckpointid = spr.stepcheckpointid
                     WHERE spr.stepcheckpointid = '{0}' AND c.containerstatus = 1 AND c.containertype !='2'", stepCheckPointID);
        if (!string.IsNullOrWhiteSpace(startTime))
        {
            sql.AppendFormat(" AND to_char(spr.createdate,'YYYY-MM-DD') >= '{0}'", startTime);
        }
        if (!string.IsNullOrWhiteSpace(endTime))
        {
            sql.AppendFormat(" AND to_char(spr.createdate,'YYYY-MM-DD') <= '{0}'", endTime);
        }
        sql.AppendLine(" ORDER BY spr.createdate");
        dtCheckPointResult = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        if (dtCheckPointResult.Rows.Count == 0)
        {
            result.Result = false; result.Message = "暂无数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //获取工人录入值、以及录入值的平均值
        foreach (DataRow item in dtCheckPointResult.Rows)
        {
            List<Dictionary<string, string>> list = m_CheckPointObj.GetCheckPointValue(item["workcheckpointresultnote"].ToString());
            if (list.Count == 0)
            {
                item["currData"] = 0;
            }
            else
            {
                Dictionary<string, string> dic = list[0];
                double currBaseValue = 0;// upValue = 0, dwValue = 0; //录入值的基本值、上浮动、下浮动
                try
                {
                    currBaseValue = double.Parse(dic["baseValue"]);
                    //upValue = double.Parse(dic["upValue"]);
                    //dwValue = double.Parse(dic["dwValue"]);
                }
                catch (Exception)
                {
                    currBaseValue = 0;
                }
                item["currData"] = currBaseValue;
            }
        }
        /*
         * 计算CPK值
         * 公式： min(Tu-U,U-Ti)/3*σ 解释：取最小值(上限值Tu-平均值U,平均值U-下限值Ti)/3*σ 
         * 平均值：工人录入值总和/总数
         * σ计算：所有的（单个工人录入值-平均值）的平方的总和/总数-1，再开根号
         */
        int iCount = dtCheckPointResult.Rows.Count;//录入总数
        double totalValue = dtCheckPointResult.AsEnumerable().Sum(p => double.Parse(p["currData"].ToString()));//合计值
        double averageValue = totalValue / iCount;//平均值
        double update = double.Parse(dtCheckPointResult.Rows[0]["updata"].ToString());//上限值
        double dwdata = double.Parse(dtCheckPointResult.Rows[0]["dwdata"].ToString());//下限值
        double minDiffValue = Math.Abs(update - averageValue) > Math.Abs(averageValue - dwdata) ? Math.Abs(averageValue - dwdata) : Math.Abs(update - averageValue);//（上限值、下限值与平均值相减，取最小值）
        double s = 0;
        foreach (DataRow item in dtCheckPointResult.Rows)
        {
            double diff = Math.Abs(double.Parse(item["currData"].ToString()) - averageValue);
            s += diff > 0 ? Math.Pow(diff, 2) : 0;
        }
        s = Math.Sqrt(s / (iCount - 1));
        double cpk = Math.Round(minDiffValue / 3 * s, 3);//计算后保留三位小数
        dtCheckPointResult.Rows[0]["cpk"] = Double.IsNaN(cpk) ? "" : cpk.ToString();
        /*计算Y轴最大值，最小值*/
        double maxBaseValue = dtCheckPointResult.AsEnumerable().Max(p => double.Parse(p["currData"].ToString()));//查出最大的录入值
        double minBaseValue = dtCheckPointResult.AsEnumerable().Min(p => double.Parse(p["currData"].ToString()));//查出最小的录入值
        maxBaseValue = Math.Ceiling(maxBaseValue > update ? maxBaseValue : update) + 1;
        minBaseValue = Math.Floor(minBaseValue < dwdata ? minBaseValue : dwdata) - 1;
        dtCheckPointResult.Rows[0]["minYdata"] = minBaseValue;
        dtCheckPointResult.Rows[0]["maxYdata"] = maxBaseValue;
        dtCheckPointResult.AcceptChanges();

        dtCheckPointResult.TableName = "dtCheckPointResult";
        result.DBDataSet.Tables.Add(dtCheckPointResult);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工序列表数据
    /// </summary>
    /// <param name="context"></param>
    public void GetWorflowStepListData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string workflowID = context.Request["workflowID"].ToString();
        result.DBTable = m_CommonObj.GetWorkFlowSetpsByWorkflowID(workflowID);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取检测项下拉数据（通过工序）
    /// </summary>
    /// <param name="context"></param>
    public void GetStepCheckPointDataByStepId(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string workflowstepId = context.Request["workflowstepId"].ToString();
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT sp.name,sp.stepcheckpointid,sp.checktype,sp.checkpointnote,sp.checkpointnotedis,sp.keycheck,sp.name,sp.DrawingRequire,sp.DrawingRequireDis,
DECODE(sp.CHECKTYPE, '3', '设计特性', '4', '过程参数', CHECKTYPE) CHECKTYPENAME,
DECODE(sp.KEYCHECK, '1', '是', '0', '否', KEYCHECK) KEYCHECKNAME,
DECODE(sp.MEOPCHECK, '1', '是', '0', '否', MEOPCHECK) MEOPCHECKNAME,
DECODE(sp.QUALITYCHECK, '1', '是', '0', '否', QUALITYCHECK) QUALITYCHECKNAME,
DECODE(sp.TCCHECKPOINTNOTE, NULL, '否', '是') ISTCM
FROM STEPCHECKPOINT sp
WHERE sp.workflowstepid = '{0}' AND sp.IsSPC = 1", workflowstepId);
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 初始化SPC异常预警页面
    /// </summary>
    /// <param name="context"></param>
    public void InitSpcWarningData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = false, Message = "暂无权限" };
        if (m_UserInfo.Roles.Contains("SPC处理员"))
        {
            result.Result = true;
            result.ReturnData = "1";
        }
        else if (m_UserInfo.Roles.Contains("SPC审核员"))
        {
            result.Result = true;
            result.ReturnData = "2";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取检测项SPC异常预警数据
    /// </summary>
    /// <param name="context"></param>
    public void GetSpcWarningData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductID", context.Request["productID"].ToString());
        para.Add("WorkflowID", context.Request["workflowID"].ToString());
        para.Add("SpecNo", context.Request["specNo"].ToString());
        para.Add("WarningTime", context.Request["warningTime"].ToString());//异常时间
        para.Add("DealTime", context.Request["dealTime"].ToString());//处理时间
        para.Add("ExamineTime", context.Request["examineTime"].ToString());//审核时间
        para.Add("dealName", context.Request["examineTime"].ToString());//处理人
        para.Add("examineName", context.Request["examineTime"].ToString());//审核人
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("PageIndex", context.Request["pageIndex"].ToString());
        result = m_CheckPointObj.GetStepCheckPointSpcWarningData(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 初始化失控处理弹窗页面填写数据
    /// </summary>
    /// <param name="context"></param>
    public void InitSpcWarningDialogData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        if (!m_UserInfo.Roles.Contains("SPC处理员"))
        {
            result.Result = false;
            result.Message = "暂无处理权限";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string stepCheckResultID = context.Request["stepCheckResultID"].ToString();
        string sql = string.Format(@"SELECT 1 FROM SpcStepCheckItemDeal spc 
WHERE spc.stepcheckpointresultid = '{0}' AND spc.status IN (2,3)", stepCheckResultID);
        if (DatabaseHelper.Query_ReturnDatTable(sql).Rows.Count > 0)
        {
            result.Result = false;
            result.Message = "该检测项已存在失控处理记录";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ExcuteEntity exuteEntity1 = new ExcuteEntity("SpcDealExperiencePool", ExcuteEntity.ExcuteTypeEnum.selectAll);
        List<FieldEntity> excuteFieldList1 = new List<FieldEntity>();
        excuteFieldList1.Add(new FieldEntity("outcontrol", "", FieldEntity.FieldTypeEnum.Str));
        excuteFieldList1.Add(new FieldEntity("dealmeasure", "", FieldEntity.FieldTypeEnum.Str));
        excuteFieldList1.Add(new FieldEntity("CreateDate", "", FieldEntity.FieldTypeEnum.Str));
        exuteEntity1.ExcuteFileds = excuteFieldList1;
        DataTable dt = DatabaseHelper.QueryDataByEntity(exuteEntity1);
        dt.DefaultView.Sort = "CreateDate desc";
        //DataTable dtReason = new DataTable(); DataTable dtSolution = new DataTable();
        //if (dt.Select("DealType=1").Length > 0)
        //{
        //    dtReason = dt.Select("DealType=1").CopyToDataTable();
        //}
        //dtReason.TableName = "dtReason";
        //result.DBDataSet.Tables.Add(dtReason);
        //if (dt.Select("DealType=2").Length > 0)
        //{
        //    dtSolution = dt.Select("DealType=2").CopyToDataTable();
        //}
        //dtSolution.TableName = "dtSolution";
        //result.DBDataSet.Tables.Add(dtSolution);
        result.DBTable = dt;
        result.ReturnData = m_UserInfo.FullName;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查看SPC处理意见
    /// </summary>
    /// <param name="context"></param>
    public void ViewSpcStepCheckItemDeal(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string stepCheckResultID = context.Request["stepCheckResultID"].ToString();
        string sql = string.Format(@"SELECT spc.*,e.fullname FROM SpcStepCheckItemDeal spc 
LEFT JOIN employee e ON e.employeeid = spc.createempid
WHERE spc.stepcheckpointresultid = '{0}' order by spc.CreateDate desc", stepCheckResultID);
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dt.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "该检测项未有失控处理记录";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        Dictionary<string, string> dic = new Dictionary<string, string>();
        if (dt.Rows[0]["Status"].ToString() == "2") //如果是厂内处理，即待审核状态
        {
            dic.Add("IsShowDealBtn", "1");//显示弹窗按钮
        }
        else
        {
            dic.Add("IsShowDealBtn", "0");//不显示弹窗按钮
        }
        dic.Add("SpcStepCheckItemDealID", dt.Rows[0]["spcstepcheckitemdealid"].ToString());
        dic.Add("OutControl", dt.Rows[0]["OutControl"].ToString());
        dic.Add("DealMeasure", dt.Rows[0]["DealMeasure"].ToString());
        dic.Add("FullName", dt.Rows[0]["fullname"].ToString());
        dic.Add("DealDate", dt.Rows[0]["DealDate"].ToString());
        dic.Add("DealOpinion", dt.Rows[0]["DealOpinion"].ToString());
        result.ReturnData = dic;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存SPC处理记录
    /// </summary>
    /// <param name="context"></param>
    public void SaveSpcStepCheckItemDeal(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string stepCheckResultID = context.Request["stepCheckResultID"].ToString();
        string warnReason = context.Request["warnReason"].ToString();
        string solution = context.Request["solution"].ToString();
        DateTime dealTime = DateTime.Now;
        if (!string.IsNullOrWhiteSpace(context.Request["dealTime"].ToString()))
        {
            dealTime = DateTime.Parse(context.Request["dealTime"].ToString());
        }
        //查询是否存在已经处理的数据
        string sql = string.Format("SELECT 1 FROM SpcStepCheckItemDeal sci WHERE sci.stepcheckpointresultid = '{0}' AND sci.isuse = 0 AND sci.status = 2", stepCheckResultID);
        if (DatabaseHelper.GetSingle(sql) != null)
        {
            result.Result = false; result.Message = "已存在处理记录，请刷新页面";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //将之前的记录置为无效
        sql = string.Format("UPDATE SpcStepCheckItemDeal sci SET sci.isuse = 1 WHERE sci.stepcheckpointresultid = '{0}'", stepCheckResultID);
        DatabaseHelper.ExecuteSql(sql);
        //添加最新数据
        ExcuteEntity exuteEntity = new ExcuteEntity("SpcStepCheckItemDeal", ExcuteEntity.ExcuteTypeEnum.insert);
        List<FieldEntity> excuteFieldList = new List<FieldEntity>();
        excuteFieldList.Add(new FieldEntity("stepcheckpointresultID", stepCheckResultID, FieldEntity.FieldTypeEnum.Str));
        excuteFieldList.Add(new FieldEntity("SpcStepCheckItemDealID", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
        excuteFieldList.Add(new FieldEntity("OutControl", warnReason, FieldEntity.FieldTypeEnum.Str));
        excuteFieldList.Add(new FieldEntity("DealMeasure", solution, FieldEntity.FieldTypeEnum.Str));
        excuteFieldList.Add(new FieldEntity("Status", 2, FieldEntity.FieldTypeEnum.Numer));
        excuteFieldList.Add(new FieldEntity("IsUse", 0, FieldEntity.FieldTypeEnum.Numer));
        excuteFieldList.Add(new FieldEntity("DealDate", dealTime, FieldEntity.FieldTypeEnum.DateTime));
        excuteFieldList.Add(new FieldEntity("CreateEmpID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
        excuteFieldList.Add(new FieldEntity("CreateDate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
        exuteEntity.ExcuteFileds = excuteFieldList;
        result.Result = DatabaseHelper.ExecuteDataByEntity(exuteEntity);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存Spc历史处理经验
    /// </summary>
    /// <param name="context"></param>
    public void SaveSpcHistoryExperienceData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string warnReason = context.Request["warnReason"].ToString();
        string solution = context.Request["solution"].ToString();
        string sql = "select 1 from SpcDealExperiencePool s where s.outcontrol = '{0}' and s.dealmeasure = '{1}'";
        sql = string.Format(sql, warnReason, solution);
        if (DatabaseHelper.GetSingle(sql) != null)
        {
            result.Result = false;
            result.Message = "存在相同的历史经验";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string spcDealExperiencePoolID = "";
        if (context.Request.Form.AllKeys.Contains("spcDealExperiencePoolID"))
        {
            spcDealExperiencePoolID = context.Request["spcDealExperiencePoolID"].ToString();
        }
        if (string.IsNullOrWhiteSpace(spcDealExperiencePoolID))
        {
            ExcuteEntity exuteEntity = new ExcuteEntity("SpcDealExperiencePool", ExcuteEntity.ExcuteTypeEnum.insert);
            List<FieldEntity> excuteFieldList = new List<FieldEntity>();
            excuteFieldList.Add(new FieldEntity("SpcDealExperiencePoolID", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("outcontrol", warnReason, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("dealmeasure", solution, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("CreateEmpID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("CreateDate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
            exuteEntity.ExcuteFileds = excuteFieldList;
            result.Result = DatabaseHelper.ExecuteDataByEntity(exuteEntity);
        }
        else
        {
            ExcuteEntity exuteEntity = new ExcuteEntity("SpcDealExperiencePool", ExcuteEntity.ExcuteTypeEnum.update);
            exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("spcdealexperiencepoolid", spcDealExperiencePoolID, FieldEntity.FieldTypeEnum.Str) };
            List<FieldEntity> excuteFieldList = new List<FieldEntity>();
            excuteFieldList.Add(new FieldEntity("outcontrol", warnReason, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("dealmeasure", solution, FieldEntity.FieldTypeEnum.Str));
            exuteEntity.ExcuteFileds = excuteFieldList;
            result.Result = DatabaseHelper.ExecuteDataByEntity(exuteEntity);
        }
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 删除SPC失控历史经验
    /// </summary>
    /// <param name="context"></param>
    public void DeleSpcHistoryExperienceData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDt"].ToString());
        string ids = "";
        foreach (DataRow item in paramDt.Rows)
        {
            ids += string.Format("'{0}',", item["spcdealexperiencepoolid"].ToString());
        }
        ids = ids.TrimEnd(',');
        string sql = string.Format("DELETE SpcDealExperiencePool s WHERE s.spcdealexperiencepoolid IN ({0})", ids);
        result.Result = DatabaseHelper.ExecuteSql(sql) > 0;
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存SPC失控处理审核结果
    /// </summary>
    /// <param name="context"></param>
    public void SaveSpcStepCheckDealResult(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        if (!m_UserInfo.Roles.Contains("SPC审核员"))
        {
            result.Result = false;
            result.Message = "暂无审核权限";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string dealOpinion = context.Request["dealOpinion"].ToString();
        string spcStepCheckItemDealID = context.Request["spcStepCheckItemDealID"].ToString();
        int type = int.Parse(context.Request["type"].ToString());
        if (type != 1 && type != 3)
        {
            result.Result = false;
            result.Message = "无法识别操作类型";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ExcuteEntity exuteEntity = new ExcuteEntity("SpcStepCheckItemDeal", ExcuteEntity.ExcuteTypeEnum.update);
        exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("SpcStepCheckItemDealID", spcStepCheckItemDealID, FieldEntity.FieldTypeEnum.Str) };
        List<FieldEntity> excuteFieldList = new List<FieldEntity>();
        excuteFieldList.Add(new FieldEntity("DealOpinion", dealOpinion, FieldEntity.FieldTypeEnum.Str));
        excuteFieldList.Add(new FieldEntity("ExamineDate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
        excuteFieldList.Add(new FieldEntity("Status", type, FieldEntity.FieldTypeEnum.Numer));
        exuteEntity.ExcuteFileds = excuteFieldList;
        result.Result = DatabaseHelper.ExecuteDataByEntity(exuteEntity);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取SPC处理历史经验库 
    /// </summary>
    /// <param name="context"></param>
    public void GetSpcDealExperiencePool(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        StringBuilder sql = new StringBuilder();
        sql.AppendLine(@"SELECT s.*,e.fullname FROM SpcDealExperiencePool s 
                       LEFT JOIN employee e ON e.employeeid = s.createempid WHERE 1=1 ");
        string experience = context.Request["experience"].ToString();
        string createName = context.Request["createName"].ToString();
        string createDate = context.Request["createDate"].ToString();
        if (!string.IsNullOrWhiteSpace(experience))
        {
            sql.AppendFormat(" AND (s.outcontrol like '{0}%' or s.dealmeasure like '{0}%')", experience);
        }
        if (!string.IsNullOrWhiteSpace(createName))
        {
            sql.AppendFormat(" AND (e.fullname like '{0}%' or e.employeename like '{0}%')", createName);
        }
        if (!string.IsNullOrWhiteSpace(createDate))
        {
            sql.AppendFormat(" AND to_char(s.createdate,'YYYY-MM-DD') = '{0}'", createName);
        }
        uMESPagingDataDTO page = new uMESPagingDataDTO();
        page.PageSize = int.Parse(context.Request["pageSize"].ToString());
        page.CurrentPageIndex = int.Parse(context.Request["pageIndex"].ToString());
        page.strSQL = sql.ToString();
        result = DatabaseHelper.RunProcedureForPage(page);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取检测项SPC基础数据
    /// </summary>
    /// <param name="context"></param>
    public void GetStepCheckInfoData(HttpContext context)
    {
        var sql = @"SELECT w.WORKFLOWSTEPNAME,s.NAME,s.BASEVALUE,s.FLOORFLOAT,s.CEILFLOAT,s.SPCTYPE,s.SPCRULE,nvl(s.ISSPC,0) ISSPC,s3.STEPINFONAME 
                FROM StepCheckPoint s
                LEFT JOIN WORKFLOWSTEP w ON w.WORKFLOWSTEPID =s.WORKFLOWSTEPID
                LEFT JOIN STEPINFO s2 ON s2.STEPINFOID =s.STEPINFOID 
                LEFT JOIN STEPINFOBASE s3 ON s3.STEPINFOBASEID =s2.STEPINFOBASEID 
                WHERE s.STEPCHECKPOINTID ='" + context.Request["StepCheckInfo"].ToString() + "'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    /// <summary>
    /// 检测项SPC基础数据保存 add by longb 2023-02-22
    /// </summary>
    /// <param name="context"></param>
    public void SaveStepCheckPointSpcData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        if (dic["ISSPC"] == "1")
        {
            if (string.IsNullOrWhiteSpace(dic["BASEVALUE"]) || string.IsNullOrWhiteSpace(dic["FLOORFLOAT"])
                || string.IsNullOrWhiteSpace(dic["CEILFLOAT"]) || string.IsNullOrWhiteSpace(dic["SPCRULE"]))
            {
                result.Result = false; result.Message = "";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }
        var updateSQL = @"update StepCheckPoint set BASEVALUE='{0}',FLOORFLOAT='{1}',CEILFLOAT='{2}',SPCTYPE='{3}',SPCRULE='{4}',ISSPC='{5}' where STEPCHECKPOINTID='{6}'";
        var c = DatabaseHelper.ExecuteSql(string.Format(updateSQL, dic["BASEVALUE"], dic["FLOORFLOAT"], dic["CEILFLOAT"], dic["SPCTYPE"], dic["SPCRULE"], dic["ISSPC"], dic["STEPCHECKPOINTID"]));
        result.Result = c > 0;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}